#include <sunwindow/window_hs.h>
#include <fcntl.h>
#include <sunwindow/win_ioctl.h>
#include <sys/ioctl.h>
#include <sundev/kbd.h>
#include <sundev/kbio.h>

/*
* sunwindow.c: things to ugly to do in C++
*/

typedef int BOOL;

int _sunwindow_ttychars(backspace, rubout)
char *backspace, *rubout;
{
	struct sgttyb ttyBuf;
	struct tchars tcharBuf;
	struct ltchars ltcharBuf;
	int fd;

	if ((fd= open("/dev/tty", O_RDONLY)) < 0)
		return 1;

	if (ioctl(fd, (int) TIOCGETP, (char*) &ttyBuf) == -1 ||
			ioctl(fd, (int) TIOCGETC, (char*) &tcharBuf) == -1 ||
				ioctl(fd, (int) TIOCGLTC, (char*) &ltcharBuf) == -1) {
		close(fd);
		return 1;
	}
	close(fd);

	*backspace= ttyBuf.sg_erase;
	*rubout= tcharBuf.t_intrc;
	return 0;
}

void _sunwindow_setmask(fd)
int fd;
{
	register short i;
	struct inputmask Mask;

	input_imnull(&Mask);
	Mask.im_flags= IM_ASCII | IM_NEGEVENT | IM_META;

	for(i = KEY_LEFTFIRST; i <= VKEY_LASTFUNC; i++)
		win_setinputcodebit(&Mask,i);
	for(i = BUT_FIRST; i <= BUT_LAST; i++)
		win_setinputcodebit(&Mask,i);
	win_setinputcodebit(&Mask, LOC_WINENTER);
	win_setinputcodebit(&Mask, LOC_WINEXIT);
	win_setinputcodebit(&Mask, LOC_MOVE);
	win_setinputcodebit(&Mask, LOC_MOVEWHILEBUTDOWN);
	win_setinputmask(fd, &Mask, (struct inputmask*) 0, WIN_NULLLINK);
}

void _sunwindow_setcursor(fd, crs)
int fd;
struct _cursor *crs;
{
	ioctl(fd, WINSETCURSOR, crs);
}

void _sunwindow_setmouse(fd, x, y, m)
int fd, x, y;
BOOL m;
{
	if (m) {
		x+= win_get_vuid_value(fd, LOC_X_ABSOLUTE);
		y+= win_get_vuid_value(fd, LOC_Y_ABSOLUTE);
	}
	win_setmouseposition(fd, x, y);
}

void _sunwindow_bell(fd, duration)
int fd;
long duration;
{
	struct screen screen;
	int kbdfd, cmd;

	win_screenget(fd, &screen);
	if ((kbdfd= open(screen.scr_kbdname, O_RDWR, 0)) < 0)
		return;
	cmd= KBD_CMD_BELL;
	ioctl(kbdfd, KIOCCMD, &cmd);
	unix_select(0, 0, 0, duration);
	cmd= KBD_CMD_NOBELL;
	ioctl(kbdfd, KIOCCMD, &cmd);
	close(kbdfd);
}

